import TopNav from "@/components/TopNav/index.vue"
import {
    addCart,
    getShopDetail,
    getCommentList,
    getBuyNowOrderNumber,
    addCollection,
    deleteCollectByIds
} from "../../../api/index"
import {getToken} from '@u/token.js'

export default {
    components: {
        TopNav
    },
    data() {
        let verificationName = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("姓名不能为空"))
            } else {
                callback()
            }
        }
        let verificationPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("手机号不能为空"))
            } else {
                const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                if (reg.test(value)) {
                    callback()
                } else {
                    return callback(new Error("请输入正确的手机号"))
                }
            }
        }
        let verificationPhoneCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空"))
            } else {
                callback()
            }
        }
        return {
            BaseUrl: process.env.VUE_APP_WAREHOUSE_API,
            src: require("../../../assets/test02.jpg"),
            num: 1, // 计数器
            radio: 1, // 信息/评论
            commentType: "", // 好评|中评|差评
            page: 1, // 分页 当前页
            pageSize: 5, // 分页 每页显示条数
            total: 0, // 分页 总条数
            onTrial: false, // 试用弹出框
            addTips: false, // 加入购物车成功弹窗
            dialogForm: {
                // 试用弹出框内表单
                name: "",
                phone: "",
                phoneCode: ""
            },
            CommentList: [], // 评论列表
            shopDetails: {}, // 商品详情,
            rules: {
                // 表单验证
                name: [
                    {required: true, validator: verificationName, trigger: "blur"}
                ],
                phone: [
                    {required: true, validator: verificationPhone, trigger: "blur"}
                ],
                phoneCode: [
                    {required: true, validator: verificationPhoneCode, trigger: "blur"}
                ]
            }
        }
    },
    methods: {
        // 修改数量
        handleChange(value) {
            this.shopDetails.price = (this.shopDetails.unitPrice * 1 * value).toFixed(
                2
            )
        },

        // 信息/评论 切换
        handleTabChange() {
            // 当点击评论的时候才去发送获取评论的请求
            if (this.radio == 2) {
                // 如果不是第一次点击评论则不发送请求
                if (this.CommentList.length <= 0) {
                    this.handleGetComment()
                }
            }
        },

        // 评论排序 从高到低
        compare(property) {
            return function (a, b) {
                let value1 = a[property]
                let value2 = b[property]
                return value2 - value1
            }
        },

        // 获取评论列表
        handleGetComment() {
            const loading = this.$loading({
                lock: true,
                text: "正在获取评论...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            })
            getCommentList({
                commodityId: this.shopDetails.id,
                pageNum: this.page,
                pageSize: this.pageSize,
                commentGrade: this.commentType ? this.commentType : null
            }).then(res => {
                if (res.data.code === 200) {

                    this.CommentList = res.data.result.list.sort(this.compare("commentGrade"))
                    this.total = res.data.result.total
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
                loading.close()
            }).catch(err => {
                // this.$message.error("获取评论失败！");
                loading.close()
            })
        },

        // 分页  每页显示多少条
        handleSizeChange(val) {
            this.pageSize = val
            this.handleGetComment()
        },

        // 分页 当前页
        handleCurrentChange(val) {
            this.page = val
            this.handleGetComment()
        },

        // 头像加载错误
        errorHandler() {
            return true
        },

        // 加入购物车
        handleAddCart() {
            let token = getToken()
            if (!token) {
                this.$confirm('您还没有登录，请先登录一下吧', '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    window.location.href = process.env.VUE_APP_LOGIN_URL
                    localStorage.setItem("isRoute", "false")
                }).catch(() => {
                    // 点击取消
                })
                return false
            }
            const loading = this.$loading({
                lock: true,
                text: "正在加入购物车...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            })
            addCart({
                goodId: this.shopDetails.id,
                projectId: this.shopDetails.projectId,
                payCount: this.num,
                serviceType:this.shopDetails.beOverdue,
                goodsType: 1
            }).then(res => {
                if (res.data.code === 200) {
                    this.addTips = true
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
                loading.close()
            }).catch(err => {
                // this.$message.error("加入购物车失败");
                loading.close()
            })
        },

        // 获取详情
        handleDateil() {
            const loading = this.$loading({
                lock: true,
                text: "详情获取中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            })
            getShopDetail({
                id: this.$route.query.id
            }).then(res => {
                if (res.data.code === 200) {
                    this.shopDetails = res.data.result
                    this.shopDetails.unitPrice = this.shopDetails.price
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
                loading.close()
            }).catch(err => {
                loading.close()
                // this.$message.error("获取详情失败");
            })
        },

        // 7天试用提交
        handleOnTrialSubmit() {
            this.$refs.dialogForm.validate(valid => {
                if (valid) {
                    this.$message({
                        message: "提交成功",
                        type: "success"
                    })
                    this.onTrial = false
                } else {
                    console.log("error submit!!")
                    return false
                }
            })
        },

        // 7 天试用取消
        handleOnTrialCancel() {
            this.$refs.dialogForm.resetFields()
            this.onTrial = false
        },

        // 立即购买
        handleBuyNow() {
            let token = getToken()
            if (!token) {
                this.$confirm('您还没有登录，请先登录一下吧', '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    window.location.href = process.env.VUE_APP_LOGIN_URL
                    localStorage.setItem("isRoute", "false")
                }).catch(() => {
                    // 点击取消
                })
                return false
            }
            const loading = this.$loading({
                lock: true,
                text: "正在获取...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            })
            getBuyNowOrderNumber({
                commodityId: this.shopDetails.id,
                payCount: this.num
            }).then(res => {
                if (res.data.code === 200) {
                    this.$router.push({
                        path: "/order",
                        query: {
                            orderNumber: res.data.result
                        }
                    })
                } else {
                    this.$message({
                        message: "获取订单号失败，请联系管理员",
                        type: "warning"
                    })
                }
                loading.close()
            })
                .catch(err => {
                    loading.close()
                    // this.$message.error("获取订单号失败，请联系管理员"+err)
                })
        },

        // 点击收藏
        handleCollection() {
            let result = new Array()
            result.push({commodityId: this.shopDetails.id})
            if (this.flage != 1) {
                const loading = this.$loading({
                    lock: true,
                    text: "正在加入收藏夹...",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)"
                })
                addCollection(result)
                    .then(res => {
                        if (res.data.code === 200) {
                            this.$message({
                                message: "加入成功",
                                type: "success"
                            })
                            this.shopDetails.flag = 1
                        } else {
                            this.$message(res.data.msg)
                        }
                        loading.close()
                    }).catch(err => {
                    loading.close()
                    // this.$message.error('加入收藏失败'+err)
                })
            }
        },

        // 好评，中评，差评勾选
        handleSort(val) {
            this.handleGetComment()
        }
    },
    created() {
        this.handleDateil()

    }
}
